﻿/*
* This file is part of WinMergeFS.
*
* WinMergeFS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.

* WinMergeFS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WinMergeFS.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinMergeFS.Common;

namespace WinMergeFS.W32
{
    class LogHandler
    {
        private string _logfile = "console";
        private LogLevel _loglevel = LogLevel.info;
        public string logfile
        {
            get
            {
                return _logfile;
            }
            set
            {
                _logfile = value;
            }
        }

        public LogLevel loglevel
        {
            get
            {
                return _loglevel;
            }
            set
            {
                _loglevel = value;
            }
        }

        public void doLogging(string message, WinMergeFS.Common.LogLevel level)
        {
            if ((int)_loglevel >= (int)level)
            {

                if (_logfile == "console")
                {
                    Console.WriteLine(level.ToString().ToUpper() + ": " + new String(' ', 5 - level.ToString().Length) + message);
                }
                else if (_logfile == "none")
                {
                }
                else // file
                {
                    //workaround for FileInUse (wait untill the file is free)
                    bool success = false;
                    while (!success)
                    {
                        try
                        {
                            System.IO.File.AppendAllText(_logfile, level.ToString().ToUpper() + ": " + message + "\r\n");
                            success = true;
                        }
                        catch (Exception)
                        {
                            //wait 50ms until trying again
                            System.Threading.Thread.Sleep(50);
                        }
                    }
                }
            }
        }
    }
}
